﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using NHibernate;
using NHibernate.Linq;

using ZQNB.Common;
using ZQNB.Entity.Accounts;
using ZQNB.Entity.Dics;
using ZQNB.Entity.Users;

namespace ZQNB.BaseLib.Users.Impl
{
    public class TeacherService : ITeacherService
    {
        private readonly ISession session;

        public TeacherService(ISession session)
        {
            this.session = session;
        }

        public IList<Teacher> GetAll()
        {
            var queryable = session.Query<Teacher>();
            return queryable.ToList();
        }
        
        public IList<Teacher> GetBySubject(string subjectCode)
        {
            var teachers = session.Query<Teacher>();
            var teacherSubjects = session.Query<TeacherSubject>();
            var accounts = session.Query<Account>();
            //var subject = session.Query<DicItem>();

            var result = from teacher in teachers
                         join teacherSubject in teacherSubjects on teacher.Id equals teacherSubject.Teacher.Id
                         join account in accounts on teacher.LoginName equals account.LoginName
                         where teacherSubject.GradeCode.StartsWith("2")
                         select teacher;

            return result.ToList();
        }

        public MessageResult SaveOrUpdate(Teacher teacher)
        {
            var messageResult = new MessageResult();
            using (var t = session.BeginTransaction())
            {
                session.SaveOrUpdate(teacher);
                t.Commit();

                messageResult.Success = true;
                messageResult.Message = "OK";
                return messageResult;
            }
        }
    }
}
